package com.jar.exercise.集合和数据结构.链表;

/**
 * @author ZhangShengHao
 * @className LinkedList
 * @description TODO
 * @date 2020/2/24 21:02
 */
public class LinkedList {
	public Node head;
	private int count;

	/**
	 * 添加节点
	 */
	public void add(String data) {
		Node node = new Node(data);
		if (head == null) {
			this.head = node;

		} else {
			Node p = this.head;
			while (p.next != null) {
				p = p.next;
			}
			p.next = node;
		}
	}

	public void remove(Integer index) {
		int flag = 0;
		Node head = this.head;
		Node end = head.next;
		if (index == 0) {
			this.head = end;
			head.next = null;
		}
		while (head != null) {
			flag++;
			if (index == flag) {
				Node p = end;
				p = p.next;
				head.next = p;
				p.next = null;
			}
			head = head.next;
			end = end.next;
		}
	}

	public void insert(Integer index, String data) {
		Node newNode = new Node(data);
		//头节点
		Node node = this.head;
		//头的下一个节点
		Node next = node.next;
		int flag = 0;
		if (index == 0) {
			this.head = newNode;
			newNode.next = node;
			return;
		}
		while (node != null) {
			flag++;
			if (index == flag) {
				node.next = newNode;
				newNode.next = next;
				break;
			}
			node = node.next;
			next = next.next;
		}
	}

	/**
	 * 返回链表的总长度
	 */
	public int size() {
		Node node = this.head;
		if (node != null) {
			count++;
			while (node.next != null) {
				node = node.next;
				count++;
			}
		}
		return count;
	}

	/**
	 * 得到指定索引的数据
	 */
	public String get(Integer index) {
		Node node = this.head;
		int flag = 0;
		while (node != null) {
			if (flag == index) {
				return node.toString();
			}
			flag++;
			node = node.next;
		}
		return null;
	}

	/**
	 * 打印链表数据
	 */
	public void pringLinked() {
		Node node = this.head;
		while (node != null) {
			System.out.println(node);
			node = node.next;
		}
	}

	/**
	 * 清除数据
	 */
	public void clear() {
		this.head = null;
	}

	/**
	 * 给指定索引位置赋值
	 */
	public void set(Integer index, String data) {
		Node node = this.head;
		int flag = 0;
		while (node != null) {
			if (index == flag) {
				node.data = data;
				break;
			}
			flag++;
			node = node.next;
		}
	}


}

class testMain {
	public static void main(String[] args) {
		LinkedList linkedList = new LinkedList();
		linkedList.add("张胜豪");
		linkedList.add("李佳奇");
		linkedList.add("诸葛亮");
		linkedList.add("asdf");
		linkedList.pringLinked();
		System.out.println();
		linkedList.remove(0);
		linkedList.pringLinked();
	}
}
